package org.example.audio;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.example.RtspInfo;

import java.nio.ShortBuffer;

/**
 * 获取实时音频
 * @author zehua
 * @date 2023/11/7 9:54
 * @Description TODO
 * @since V1.1.0
 */

public class AudioStreamHandler {

    public static void main(String[] args) {
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(RtspInfo.RTSP_URL_CAMERA);

        try {
            grabber.start();
            Frame frame;
            int i=0;
            while ((frame = grabber.grab()) != null) {
                i++;
                if (i%30 == 0 && frame.samples != null) {
                    // 处理音频帧
                    double volume = calculateVolume(frame.samples);
                    // 录制音频

                    // TOOD 对比
                    System.out.println("Volume: " + volume);
                }
            }
        } catch (FFmpegFrameGrabber.Exception e) {
            e.printStackTrace();
        } finally {
            try {
                grabber.stop();
            } catch (FFmpegFrameGrabber.Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 计算音频帧的音量
     *
     * @param samples 音频样本
     * @return 音量值
     */
    private static double calculateVolume(Object[] samples) {
        double sum = 0;
        long totalSamples = 0;

        for (Object sample : samples) {
            if (sample instanceof ShortBuffer) {
                ShortBuffer buffer = (ShortBuffer) sample;
                int remaining = buffer.remaining();
                totalSamples += remaining;

                while (buffer.hasRemaining()) {
                    short data = buffer.get();
                    sum += data * data;
                }
                buffer.rewind(); // Rewind the buffer for the next read if necessary
            }
        }

        if (totalSamples > 0) {
            double mean = sum / totalSamples;
            return Math.sqrt(mean);
        }
        return 0;
    }



}

